<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Kame
 * Date: 24/03/13
 * Time: 09:47 PM
 */

namespace Site\Model;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;

class PointTable {
    protected $tableGateway;

    public function __construct(TableGateway $gateway)
    {
        $this->tableGateway = $gateway;
    }

    public function fetchAll()
    {
        return $this->tableGateway->select();
    }

    public function fetchAllPublic(){
        return $this->tableGateway->select(array('espublico' => true));
    }

    public function getPointByID($punto)
    {
        $punto = (int)$punto;
        return $this->tableGateway->select(array('punto' => $punto));
    }

    public function getPointByUser($usuario)
    {
        $usuario = (int)$usuario;
        return $this->tableGateway->select(array('usuario' => $usuario));
    }

    public function getPointByNick($nick){

        $result  = $this->tableGateway->select(function (Select $select) use ($nick){
            $select->where(array('nick'=>$nick));
            $select->join('usuario', 'punto.usuario = usuario.usuario');
        });
        return $result;
    }


    public function getPointByName($nombre)
    {
        return $this->tableGateway->select(array('nombre' => $nombre));
    }

    public function getPointByCoordinates($latitud, $longitud, $elevacion)
    {
        $latitud = (double) $latitud;
        $longitud = (double) $longitud;
        $elevacion = (double) $elevacion;
        return $this->tableGateway->select(array(
            'latitud' => $latitud,
            'longitud' => $longitud,
            'elevacion' => $elevacion,
        ));
    }

    public function savePoint(Point $point)
    {
        $data = array(
            'latitud' => $point->latitud,
            'longitud' => $point->longitud,
            'elevacion' => $point->elevacion,
            'nombre' => $point->nombre,
            'icono' => $point->icono,
            'espublico' => $point->espublico,
            'tipo'  => $point->tipo,
            'usuario' => $point->usuario,
        );
        $punto = (int)$point->punto;
        if ($punto == 0) {
            $this->tableGateway->insert($data);
            return true;
        } else {
            if($this->getPointByID($punto)){
                $this->tableGateway->update($data,array('punto' => $punto));
                return true;
            }
        }
        return false;
    }

    public function deletePoint($punto){
        $this->tableGateway->delete(array('punto' => $punto));
    }
}